<template>
	<view style="padding: 25rpx 0 190rpx;">
		<button class="addBtn" @click="addRank">+新建代表队</button>
		<!-- 队伍管理 -->
		<!-- 已有队伍 -->
		<uni-group mode="card" :title="t.name" top="20" v-for="(t, index) in teamList" :key="t.id">
			<view class="wBox">
				<!-- 编辑 -->
				<uni-icons class="poIcon" style="right: 36px;" color="#1ec886" type="compose" size="20"  @click="editRank(t)"></uni-icons>
				<uni-icons class="poIcon" color="#DC0032" type="minus" size="20"  @click="delRank(t)"></uni-icons>


				<uni-list :border="false">
					<uni-list-item title="名称" :rightText="t.name" />
					<uni-list-item title="logo">
						<template v-slot:footer>
							<image class="rank-image" :src="t.imgUrl" mode="aspectFit"></image>
						</template>
					</uni-list-item>
					<uni-list-item title="教练" v-if="t.coachNames">
						<template v-slot:footer style="display: flex;">
							<view class="nameList">
								<text>{{ t.coachNames }}</text>
							</view>

							<!-- <uni-icons @click="goChooseCoach(t.id)" type="forward" size="16"></uni-icons> -->
						</template>
					</uni-list-item>
					<uni-list-item title="领队" v-if="t.leaderNames">
						<template v-slot:footer>
							<view class="nameList">
								<text>{{ t.leaderNames }}</text>
							</view>
						</template>
					</uni-list-item>
					<uni-list-item title="队医" v-if="t.teamDoctorNames">
						<template v-slot:footer>
							<view class="nameList">
								<text>{{ t.teamDoctorNames }}</text>
							</view>
						</template>
					</uni-list-item>
					<uni-list-item title="翻译" v-if="t.translatorNames">
						<template v-slot:footer>
							<view class="nameList">
								<text>{{ t.translatorNames }}</text>
							</view>
						</template>
					</uni-list-item>
					<uni-list-item title="官员" v-if="t.officialNames">
						<template v-slot:footer>
							<view class="nameList">
								<text>{{ t.officialNames }}</text>
							</view>
						</template>
					</uni-list-item>
					<uni-list-item title="其他" v-if="t.otherNames">
						<template v-slot:footer>
							<view class="nameList">
								<text>{{ t.otherNames }}</text>
							</view>
						</template>
					</uni-list-item>
					<uni-list-item>
						<template v-slot:body>
							<view class="flexRight">
								<button type="primary" style="font-size: 13px;padding: 0 10px;margin: 0;" plain="true"
									v-if="t.signCount==0" @click="goNext(t)">配置队员</button>
								<view class="flexBetween" v-else>
									<text class="orange">已报{{t.signCount}}人</text>
									<button type="primary" style="font-size: 13px;padding: 0 10px;margin: 0;" plain="true"
										@click="goNext(t)">修改配置</button>
								</view>
							</view>
						</template>
					</uni-list-item>
				</uni-list>
			</view>
		</uni-group>
		<view class="nodata" v-if="teamList.length == 0">
			<image mode="aspectFit" src="/static/nodata.png"></image>
			<text>还没有队伍，点击新建代表队立即创建吧~</text>
		</view>

		<uni-popup ref="popup" type="bottom" background-color="#fff">
			<view class="wBox" style="padding: 30rpx;">
				<uni-forms ref="baseForm" :modelValue="baseFormData">
					<uni-forms-item label="名称" required><uni-easyinput v-model="baseFormData.name"
							placeholder="请输入名称" /></uni-forms-item>
					<uni-forms-item label="logo" required>
						<!-- 						<view class="avatarUrl">
							<button type="default" open-type="chooseAvatar" @chooseavatar="onChooseavatar">
								<image mode="aspectFill" :src="baseFormData.imgUrl" class="refreshIcon"></image>
							</button>
						</view>
 --> <uni-file-picker v-model="baseFormData.imgUrlObj" @delete="delteamlogo" return-type="object" limit="1"
							@select="upteamlogo"></uni-file-picker>
					</uni-forms-item>

					<uni-forms-item label="教练" required v-if="coachOrLeaderFlag=='1'">
						<view @click="goChooseCoach(baseFormData)" class="fakeInput">
							<text v-if="baseFormData.coachNames">{{ baseFormData.coachNames }}</text>
							<text v-else class="placeHolder">请选择教练</text>
						</view>
					</uni-forms-item>

					<uni-forms-item label="领队" required v-if="coachOrLeaderFlag=='1'">
						<view @click="goChooseCoach(baseFormData)" class="fakeInput">
							<text v-if="baseFormData.leaderNames">{{ baseFormData.leaderNames }}</text>
							<text v-else class="placeHolder">请选择领队</text>
						</view>
					</uni-forms-item>

					<uni-forms-item label="队医" v-if="coachOrLeaderFlag=='1'">
						<view @click="goChooseCoach(baseFormData)" class="fakeInput">
							<text v-if="baseFormData.teamDoctorNames">{{ baseFormData.teamDoctorNames }}</text>
							<text v-else class="placeHolder">请选择其他</text>
						</view>
					</uni-forms-item>
					<uni-forms-item label="翻译" v-if="coachOrLeaderFlag=='1'">
						<view @click="goChooseCoach(baseFormData)" class="fakeInput">
							<text v-if="baseFormData.translatorNames">{{ baseFormData.translatorNames }}</text>
							<text v-else class="placeHolder">请选择其他</text>
						</view>
					</uni-forms-item>
					<uni-forms-item label="官员" v-if="coachOrLeaderFlag=='1'">
						<view @click="goChooseCoach(baseFormData)" class="fakeInput">
							<text v-if="baseFormData.officialNames">{{ baseFormData.officialNames }}</text>
							<text v-else class="placeHolder">请选择其他</text>
						</view>
					</uni-forms-item>
					<uni-forms-item label="其他" v-if="coachOrLeaderFlag=='1'">
						<view @click="goChooseCoach(baseFormData)" class="fakeInput">
							<text v-if="baseFormData.otherNames">{{ baseFormData.otherNames }}</text>
							<text v-else class="placeHolder">请选择其他</text>
						</view>
					</uni-forms-item>
					<view class="flexCenter">
						<button class="btn btn1" @click="saveRank(baseFormData)" type="default">保存</button>
					</view>
				</uni-forms>
			</view>
		</uni-popup>

		<view class="fixedBottom">
			<button @click="goPrev" class="btn btnKx">上一步</button>
			<button v-if="showSubmitBtn" class="btn btn1" @click="goDone" type="default">下一步</button>
		</view>
	</view>
</template>

<script setup>
	import {
		reactive,
		toRefs
	} from 'vue';
	import * as match from '@/common/match.js';
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app';
	import _ from 'lodash';
	const app = getApp();
	const data = reactive({
		baseFormData: {
			coachNames: '',
			leaderNames: '',
			otherNames: '',
			teamDoctorNames: '',
			translatorNames: '',
			officialNames: ''
		},
		groupId: '',
		teamList: [],
		chooseObj: {},
		popup: null,
		showSubmitBtn: false,
		coachOrLeaderFlag: null
	});
	const {
		baseFormData,
		groupId,
		teamList,
		chooseObj,
		popup,
		coachOrLeaderFlag,
		showSubmitBtn
	} = toRefs(data);
	let coaches = []; //团队中的已有人员
	let leaders = [];
	let others = [];
	let teamDoctors = [];
	let translators = [];
	let officials = [];
	let cptId = '';
	let chargeFlag = '';
	let signType = '2';
	let signInfoType = null
	onShow(option => {
		if (!!option) {
			// 选完人回来
			const coachsArr = option.coachsArr;
			const leadersArr = option.leadersArr;
			const othersArr = option.othersArr;
			const doctorsArr = option.doctorsArr;
			const translatorArr = option.translatorArr;
			const officialArr = option.officialArr;
			let arr = [];
			let arr2 = [];
			let arr3 = [];
			let arr4 = [];
			let arr5 = [];
			let arr6 = [];

			let nrr = [];
			let nrr2 = [];
			let nrr3 = [];
			let nrr4 = [];
			let nrr5 = [];
			let nrr6 = [];

			for (const n of coachsArr) {
				arr.push(n.id);
				nrr.push(n.realName);
			}
			baseFormData.value.coachIds = arr.toString();
			baseFormData.value.coachNames = nrr.toString();

			for (const n of leadersArr) {
				arr2.push(n.id);
				nrr2.push(n.realName);
			}
			baseFormData.value.leaderIds = arr2.toString();
			baseFormData.value.leaderNames = nrr2.toString();

			for (const n of othersArr) {
				arr3.push(n.id);
				nrr3.push(n.realName);
			}
			baseFormData.value.otherIds = arr3.toString();
			baseFormData.value.otherNames = nrr3.toString();
			for (const n of doctorsArr) {
				arr4.push(n.id);
				nrr4.push(n.realName);
			}
			baseFormData.value.teamDoctorIds = arr4.toString();
			baseFormData.value.teamDoctorNames = nrr4.toString();
			for (const n of translatorArr) {
				arr5.push(n.id);
				nrr5.push(n.realName);
			}
			baseFormData.value.translatorIds = arr5.toString();
			baseFormData.value.translatorNames = nrr5.toString();
			for (const n of officialArr) {
				arr6.push(n.id);
				nrr6.push(n.realName);
			}
			baseFormData.value.officialIds = arr6.toString();
			baseFormData.value.officialNames = nrr6.toString();
		}
		coachOrLeaderFlag.value = app.globalData.coachOrLeaderFlag
		if (groupId.value != 0) {
			getList(cptId, groupId.value);
		}
		getMySignInfo()
	});
	onLoad(option => {
		cptId = option.matchId;
		groupId.value = option.groupId;
		match.getMatchById({
			id: cptId
		}).then(res => {
			chargeFlag = res.data.chargeFlag
		})
	});

	function addRank() {
		baseFormData.value = {};
		baseFormData.value.imgUrlObj = {}
		popup.value.open();
	}

	function onChooseavatar(e) {
		match.uploadFile(e).then(data => {
			baseFormData.value.imgUrl = data.data;
		});
	}

	function upteamlogo(e) {
		match.uploadImg(e).then(data => {
			baseFormData.value.imgUrl = data.data;
		});
	}

	function delteamlogo(n) {
		baseFormData.value.imgUrl = '';
	}

	function giveMemberName(ids, list, names) {
		let arr = [];
		let idsArr = ids.split(',');
		for (const c of idsArr) {
			let nn = _.findIndex(list, function(n) {
				return n.id == c;
			});
			if (nn > -1) {
				let str = list[nn].realName;
				arr.push(str);
			}
		}
		names = arr.toString();
		console.log(names);
	}

	function giveMemberNames() {
		let arr = [];
		let arr2 = [];
		let arr3 = [];
		let arr4 = [];
		let arr5 = [];
		let arr6 = [];
		let coachsArr = baseFormData.value.coachIds.split(',');
		let leadersArr = baseFormData.value.leaderIds.split(',');
		let othersArr = baseFormData.value.otherIds.split(',');
		let teamDoctorsArr = baseFormData.value.teamDoctorIds.split(',');
		let translatorsArr = baseFormData.value.translatorIds.split(',');
		let officialsArr = baseFormData.value.officialIds.split(',');

		for (const c of coachsArr) {
			let nn = _.findIndex(coaches, function(n) {
				return n.id == c;
			});
			if (nn > -1) {
				let str = coaches[nn].realName;
				arr.push(str);
			}
		}
		for (const c of leadersArr) {
			let nn = _.findIndex(leaders, function(n) {
				return n.id == c;
			});
			if (nn > -1) {
				let str = leaders[nn].realName;
				arr2.push(str);
			}
		}
		for (const c of othersArr) {
			let nn = _.findIndex(others, function(n) {
				return n.id == c;
			});
			if (nn > -1) {
				let str = others[nn].realName;
				arr3.push(str);
			}
		}
		for (const c of teamDoctorsArr) {
			let nn = _.findIndex(teamDoctors, function(n) {
				return n.id == c;
			});
			if (nn > -1) {
				let str = teamDoctors[nn].realName;
				arr4.push(str);
			}
		}
		for (const c of translatorsArr) {
			let nn = _.findIndex(translators, function(n) {
				return n.id == c;
			});
			if (nn > -1) {
				let str = translators[nn].realName;
				arr5.push(str);
			}
		}
		for (const c of officialsArr) {
			let nn = _.findIndex(officials, function(n) {
				return n.id == c;
			});
			if (nn > -1) {
				let str = officials[nn].realName;
				arr6.push(str);
			}
		}
		baseFormData.value.coachNames = arr.toString();
		baseFormData.value.leaderNames = arr2.toString();
		baseFormData.value.otherNames = arr3.toString();
		baseFormData.value.teamDoctorNames = arr3.toString();
		baseFormData.value.translatorNames = arr3.toString();
		baseFormData.value.officialNames = arr3.toString();
	}

	function getList(a, b) {
		// 获取队伍列表
		match.getMyGroupForCpt(b, a).then(res => {
			coaches = res.data.coaches;
			leaders = res.data.leaders;
			others = res.data.others;
			teamDoctors = res.data.teamDoctors;
			translators = res.data.translators;
			officials = res.data.officials;
			match.getMyTeamList(a, b).then(response => {
				teamList.value = response.data;
			});
		});
	}

	function saveRank(form) {
		form.groupId = groupId.value;
		console.log(form);
		if (!form.name || form.name == '') {
			uni.showToast({
				title: '请填写队伍名称',
				icon: 'none',
				duration: 2000
			});
			return;
		}
		if (!form.imgUrl) {
			uni.showToast({
				title: '请上传队伍logo',
				icon: 'none',
				duration: 2000
			});
			return;
		}
		if (!form.coachNames && coachOrLeaderFlag.value == '1') {
			uni.showToast({
				title: '请至少选择一个教练',
				icon: 'none',
				duration: 2000
			});
			return;
		}
		if (!form.leaderNames && coachOrLeaderFlag.value == '1') {
			uni.showToast({
				title: '请至少选择一个领队',
				icon: 'none',
				duration: 2000
			});
			return;
		}
		form.cptId = cptId
		delete form.coachIdList
		delete form.leaderIdList
		delete form.otherIdList
		delete form.teamDoctorIdList
		delete form.translatorIdList
		delete form.officialIdList
		delete form.signCount
		delete form.imgUrlObj
		match.saveMyTeam(form).then(res => {
			popup.value.close()
			getList(cptId, groupId.value);
		});
	}

	function delRank(n) {
		if(n.signCount>0){
			uni.showToast({
				title: `已配置报项不能删除队伍`,
				icon: 'none',
				duration: 2000
			});
			return
		}
		
		uni.showModal({
			title: '提示',
			content: `确定删除${n.name}吗`,
			success: function(res) {
				if (res.confirm) {
					match.delRank(n.id).then(response => {
						getList(cptId, groupId.value);
						uni.showToast({
							icon: 'none',
							title: '操作成功',
							duration: 2000
						});
					});
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
	}
	function editRank(team) {
		console.log(team)
		baseFormData.value = team;
		if(baseFormData.value.imgUrl){
			baseFormData.value.imgUrlObj = {
				name: "logo",
				extname: "jpg",
				url: baseFormData.value.imgUrl
			}
		}
		popup.value.open();
	}
	function goNext(t) {

		// 选运动员
		let path =
			`/pages_match/match/team_choose_sportman?matchId=${cptId}&groupId=${groupId.value}&teamId=${t.id}&teamName=${t.name}`;
		uni.navigateTo({
			url: path
		});

	}

	function goChooseCoach(form) {
		var hasChooseObj = {
			coachIds: form.coachIds,
			leaderIds: form.leaderIds,
			otherIds: form.otherIds,
			teamDoctorIds: form.teamDoctorIds,
			translatorIds: form.translatorIds,
			officialIds: form.officialIds,
		};
		let path =
			`/pages_match/match/choose_coach?matchId=${cptId}&signType=${signType}&groupId=${groupId.value}&hasChooseObj=` +
			encodeURIComponent(JSON.stringify(hasChooseObj));
		uni.navigateTo({
			url: path
		});
	}

	function getMySignInfo() {
		var obj = {
			cptId: cptId,
			groupId: groupId.value
		}
		// 是否已有
		match.getMySignInfo(obj).then(res => {
			console.log(res.data)
			if (res.data.signInfo&&res.data.signInfo.length > 0) {
				showSubmitBtn.value = true
			}
			signInfoType = res.data.type
		})
	}

	function goPrev() {
		uni.navigateBack()
	}

	function goDone() {
		for (const t of teamList.value) {
			if (t.signCount == 0) {
				uni.showToast({
					title: `${t.name}没有配置人员`,
					icon: 'none',
					duration: 2000
				});
				return
			}
		}

		if (signInfoType == '1') {
			uni.showModal({
				title: '提示',
				content: '已报项，前往我的报项',
				showCancel: false,
				success: function(res) {
					if (res.confirm) {
						let path =
							`/pages/usercenter/match`;
						uni.reLaunch({
							url: path
						});
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				}
			});
			return
		}
		if (signInfoType == '2') {
			match.recoverMySign({
				cptId: cptId,
				groupId: groupId.value
			}).then(res => {
				if (res.msg.indexOf("Exception:") > -1) {
					let msg = res.msg.slice(10)
					uni.showModal({
						title: '提示',
						content: msg,
						success: function(res) {
							if (res.confirm) {
								console.log('用户点击确定');
							}
						}
					});
					return
				}
				afterRecover()
			})
		} else {
			afterRecover()
		}

	}

	function afterRecover() {
		// 判断是否收费
		if (chargeFlag == '0') {
			// 免费
			// 提交报名
			var obj = {
				cptId: cptId,
				groupId: groupId.value
			}
			match.commitSign(obj).then(res => {
				console.log(res.data)
				let path =
					`/pages_match/match/matchPayDone?cptId=${cptId}&groupId=${groupId.value}&chargeFlag=${chargeFlag}&orderId=${res.data}`;
				uni.navigateTo({
					url: path
				});
			})

		} else {
			let path = `/pages_match/match/matchBill?cptId=${cptId}&groupId=${groupId.value}`;
			uni.navigateTo({
				url: path
			});
		}
	}
</script>

<style scoped lang="scss">
	.poKxBtn {
		position: absolute;
		top: -70rpx;
		right: 0;
		font-size: 24rpx;
		line-height: 2;
	}
	.poIcon {
		position: absolute;
		top: -66rpx;
		right: 10rpx;
	}

	:deep(.uni-group__content) {
		padding: 0;
	}

	.addBtn {
		width: 700rpx;
		height: 90rpx;
		background: #ffffff;
		border: 1rpx solid $uni-color-primary;
		color: $uni-color-primary;
		font-size: 30rpx;
		border-radius: 15rpx;
	}

	.wBox {
		position: relative;
		background: #ffffff;
		border-radius: 15px;
		box-sizing: border-box;
	}

	.avatarUrl {
		width: 200rpx;
		height: 200rpx;
	}

	.avatarUrl button {
		padding: 0;
		display: block;
		line-height: 1;
	}

	.refreshIcon {
		width: 200rpx;
		height: 200rpx;
	}

	.rank-image {
		width: 120rpx;height: 120rpx;
		background: #f8f8f8;
		border-radius: 50%;
	}

	.nameList {
		text {
			font-size: 30rpx;
			color: #000000;
		}
	}

	.fakeInput {
		font-size: 14px;
		border-radius: 4px;
		border: 1px solid #e5e5e5;
		color: #333;
		padding-left: 10px;
		line-height: 35px;

		.placeHolder {
			color: #aaa;
		}
	}
</style>